<!DOCTYPE html> 
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>订单列表</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
    <style>
        .waiting-message {
            color: red;
            font-weight: bold;
            display: inline-block;
            animation: pulse 1s infinite; /* 添加动画 */
        }

        @keyframes pulse {
            0% {
                opacity: 1;
            }
            50% {
                opacity: 0.5;
            }
            100% {
                opacity: 1;
            }
        }
            /* 默认状态下的文字颜色 */
        .receiver-info {
            cursor: pointer;
            color: #171718;
        }
        body {
            background-color: #f8f9fa; /* 背景色 */
            font-family: 'Arial', sans-serif;
            font-size: 14px; /* 将字体大小稍微增大 */
        }
        .container {
            max-width: 90%; /* 修改容器宽度，使其占满屏幕的90% */
            margin: 20px auto; /* 居中显示 */
            padding: 20px;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
            background-color: white;
        }
        h1 {
            text-align: center;
            margin-bottom: 20px;
            font-size: 2rem; /* 将标题大小缩小 */
            color: #343a40;
        }
        label {
            font-weight: bold;
            margin-right: 10px;
        }
        table {
            margin-top: 20px;
            width: 100%;
            border-collapse: collapse;
        }
        th, td {
            text-align: left; /* 字体靠左显示 */
            vertical-align: middle; /* 垂直居中 */
            height: 30px; /* 行高 */
            line-height: 30px; /* 行高匹配单元格高度，确保文本垂直居中 */
        }
        th {
            background-color: #007bff; /* 表头背景颜色 */
            color: white;
        }
        tr:nth-child(even) td {
            background-color: #f1f1f1; /* 偶数行背景颜色 */
        }
        tr:nth-child(odd) td {
            background-color: #ffffff; /* 奇数行背景颜色 */
        }
        td img {
            max-width: 33px; /* 将图片宽度缩小三分之一 */
            max-height: 33px; /* 将图片高度缩小三分之一 */
            margin-right: 5px; /* 图片与文本之间的间距 */
        }
        .receiver-info {
            max-width: 600px; /* 增加收货人信息列宽 */
            white-space: normal; /* 允许换行 */
        }
        .buyer-name {
            width: 150px; /* 调整收货人信息列宽 */
        }
        .order-id {
            width: 100px; /* 设置订单ID列宽度 */
        }
        .loading {
            display: none; /* 默认隐藏加载提示 */
            position: fixed; /* 固定定位 */
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(255, 255, 255, 0.8); /* 半透明背景 */
            z-index: 999; /* 确保在最上面 */
            text-align: center; /* 居中显示 */
            align-items: center; /* 垂直居中 */
            justify-content: center; /* 水平居中 */
        }
        .loading .spinner {
            border: 8px solid rgba(0, 123, 255, 0.3); /* 边框颜色 */
            border-top: 8px solid #007bff; /* 顶部边框颜色 */
            border-radius: 50%; /* 圆形 */
            width: 50px; /* 宽度 */
            height: 50px; /* 高度 */
            animation: spin 1s linear infinite; /* 动画效果 */
        }
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
        .btn-link {
            color: #007bff;
        }
        .btn-link:hover {
            text-decoration: underline;
        }
        .pagination {
            margin-top: 20px;
            justify-content: center;
        }
        .pagination .page-item .page-link {
            border-radius: 50%;
            margin: 0 5px;
        }
        .pagination .page-item.active .page-link {
            background-color: #007bff;
            color: white;
        }
        .pagination .page-link:hover {
            background-color: #0056b3;
            color: white;
        }
        .checkbox {
            display: inline-block;
            transform: scale(1.5); /* 增大选择框 */
            margin-right: 10px; /* 增加选择框右边距 */
        }
        .order-index {
            font-size: 18px; /* 调整序号字体大小 */
            font-weight: bold; /* 加粗 */
        }
        .page-size-select {
            margin-left: 15px; /* 为选择框增加左边距 */
        }
    </style>    
</head>
<body>
    <div class="container">
        <h1>订单列表</h1>
        <div class="loading" id="loadingMessage">
            <div class="spinner"></div>
            <div>正在加载...</div>
        </div>
        
        <!-- 时间选择器 -->
        <div class="form-group d-flex justify-content-center align-items-center">
            <div class="container">
                <div class="row align-items-center mb-3">
                    <div class="col-auto">
                        <label for="startDate">开始日期:</label>
                        <input type="datetime-local" id="startDate" class="form-control" style="width: auto;">
                    </div>
                    <div class="col-auto">
                        <label for="endDate">结束日期:</label>
                        <input type="datetime-local" id="endDate" class="form-control" style="width: auto;">
                    </div>
                    <div class="col-auto">
                        <input type="text" id="searchInputID" class="form-control" placeholder="订单编号" style="width: auto;">
                    </div>
                    <div class="col-auto">
                        <input type="text" id="searchInputBuyer" class="form-control" placeholder="收货人姓名/电话" style="width: auto;">
                    </div>
                    <div class="col-auto">
                        <input type="text" id="searchInputProductInfo" class="form-control" placeholder="商品信息" style="width: auto;">
                    </div>
                    <div class="col-auto">
                        <button id="filterButton" class="btn btn-primary">查询订单</button>
                    </div>
                    <div class="col-auto">
                        <button id="exportButton" class="btn btn-success">订单信息导出</button>
                    </div>
                    <div class="col-auto">
                        <button id="triggerButton" class="btn btn-warning">批量解密信息</button>
                    </div>
                </div>
            </div>
            
        </div>
        <ul class="nav nav-tabs" id="orderTabs">
            <li class="nav-item">
                <a class="nav-link active" href="#" data-status="waitsellersend">待发货订单</a>
            </li>
            <li class="nav-item">
                <a class="nav-link" href="#" data-status="waitbuyerreceive">待买家确认收货</a>
            </li>
            <li class="nav-item">
                <a class="nav-link" href="#" data-status="success">交易成功</a>
            </li>
            <li class="nav-item">
                <a class="nav-link" href="#" data-status="cancel">交易关闭</a>
            </li>
        </ul>
        <table class="table table-bordered">
            <thead>
                <tr>
                    <th style="width: 2.4%;">序号</th>
                    <th style="width: 3%;">选择</th>
                    <th style="width: 10%;" class="order-id">订单ID</th>
                    <th style="width: 25%;" class="buyer-name">收货人信息</th>
                    <th style="width: 20%;">产品信息</th>
                    <th style="width: 8%;">数量</th>
                    <th style="width: 5%;">总金额</th>
                    <th>备注</th> <!-- 新增备注列 -->
                    <th>创建时间</th>
                </tr>
            </thead>
            <tbody id="orderTableBody"></tbody>
        </table>
        <nav>
            <ul class="pagination" id="pagination"></ul>
        </nav>
        <div class="form-group d-flex justify-content-center align-items-center">
            <label for="pageSize">每页显示条数:</label>
            <select id="pageSize" class="form-control page-size-select" style="width: auto;">
                <option value="20" selected>20</option>
                <option value="100">100</option>
                <option value="200">200</option>
            </select>
        </div>
    </div>

    <script>
        let currentPage = 1;
        let pageSize = 20; // 默认每页显示20条
        let totalRecords = 0;
        let currentStatus = "waitsellersend"; // 默认状态为待发货
    
        // 设置日期选择器的默认值
        function setDefaultDates() {
            const startDateInput = document.getElementById('startDate');
            const endDateInput = document.getElementById('endDate');
    
            const today = new Date();
            const threeMonthsAgo = new Date(today);
            threeMonthsAgo.setDate(today.getDate() - 10);
    
            const formatDate = (date) => {
                const pad = (n) => (n < 10 ? '0' + n : n);
                return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}T${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`;
            };
    
            startDateInput.value = formatDate(threeMonthsAgo);
            endDateInput.value = formatDate(today);
        }
    
        // 获取总记录数并渲染分页
        function fetchTotalRecords() {
            loadingMessage.style.display = 'flex';
            const startDate = document.getElementById('startDate').value;
            const endDate = document.getElementById('endDate').value;
            fetch(`http://localhost:8080/dataList?startDate=${startDate}&endDate=${endDate}`)
                .then(data => {
                    fetch(`http://localhost:8080/listsize?startDate=${startDate}&endDate=${endDate}&status=${currentStatus}`)
                    .then(response => response.json())
                    .then(data => {
                        if (data == 0) {
                            alert("未搜索到相符订单");
                        }
                        totalRecords = data;
                        renderPagination();
                        fetchOrders(currentPage, pageSize);
                    })
                    .catch(error => console.error('Error fetching total records:', error))
                    .finally(() => {
                        loadingMessage.style.display = 'none';
                    });
                })
                .catch(error => {
                console.error("接口调用失败", error);
                });
            
        }
    
        // 获取订单数据
        function fetchOrders(page, size) {
            const loadingMessage = document.getElementById('loadingMessage');
            loadingMessage.style.display = 'flex';
    
            const startDate = document.getElementById('startDate').value;
            const endDate = document.getElementById('endDate').value;
            const orderID = document.getElementById('searchInputID').value;
            const buyer = document.getElementById('searchInputBuyer').value;
            const productInfo = document.getElementById('searchInputProductInfo').value;
    
            const queryParams = new URLSearchParams({
                page,
                pageSize: size,
                startDate,
                endDate,
                orderID,
                buyer,
                productInfo,
                sort: 1,
                status: currentStatus,
                direction: 'create_time'
            }).toString();
            fetch(`http://localhost:8080/dataList?startDate=${startDate}&endDate=${endDate}`)
                .then(data => {
                    fetch(`http://localhost:8080/list?${queryParams}`)
                    .then(response => {
                        if (!response.ok) {
                            throw new Error('Network response was not ok');
                        }
                        return response.json();
                    })
                    .then(data => {
                        if (data.result[0] == null) {
                            alert("未搜索到相符订单");
                        } else {
                            renderTable(data.result);
                        }
                    })
                    .catch(error => console.error('Error fetching orders:', error))
                    .finally(() => {
                        loadingMessage.style.display = 'none';
                    });
                })
                .catch(error => {
                console.error("接口调用失败", error);
                });
            
        }
    
        // 渲染表格内容
        function renderTable(orders) {
            const tableBody = document.getElementById('orderTableBody');
            tableBody.innerHTML = '';
    
            orders.forEach((order, index) => {
                const row = document.createElement('tr');
                const receiverInfo = `${order.baseInfo.buyerContact.name}, ${order.baseInfo.buyerContact.mobile}, ${order.baseInfo.buyerContact.province}${order.baseInfo.buyerContact.city}${order.baseInfo.buyerContact.area}${order.baseInfo.buyerContact.address}`;
                row.innerHTML = `
                    <td>${(currentPage - 1) * pageSize + index + 1}</td>
                    <td><input type="checkbox" class="order-checkbox" data-order-id="${order.baseInfo.id}"></td>
                    <td class="order-id">${order.baseInfo.id}</td>
                    <td class="buyer-name">${receiverInfo}</td>
                    <td>
                        <img src="${order.productItems[0].productImgUrl[0]}" alt="${order.productItems[0].skuID}">
                        ${order.productItems[0].skuInfos[0].value}
                    </td>
                    <td>${order.productItems[0].quantity}</td>
                    <td>${(order.baseInfo.totalAmount / 100).toFixed(2)} 元</td>
                    <td>${order.baseInfo.remark ? order.baseInfo.remark : ''}</td>
                    <td>${new Date(order.baseInfo.createTime).toLocaleString()}</td>
                `;
                tableBody.appendChild(row);
            });
        }
    
        // 渲染分页
        function renderPagination() {
            const pagination = document.getElementById('pagination');
            pagination.innerHTML = '';
    
            const totalPages = Math.ceil(totalRecords / pageSize);
    
            const prevPageItem = document.createElement('li');
            prevPageItem.className = `page-item ${currentPage === 1 ? 'disabled' : ''}`;
            prevPageItem.innerHTML = `<a class="page-link" href="#">上一页</a>`;
            prevPageItem.onclick = (e) => {
                e.preventDefault();
                if (currentPage > 1) {
                    currentPage--;
                    fetchOrders(currentPage, pageSize);
                    renderPagination();
                }
            };
            pagination.appendChild(prevPageItem);
    
            for (let i = 1; i <= totalPages; i++) {
                const pageItem = document.createElement('li');
                pageItem.className = 'page-item';
                if (i === currentPage) {
                    pageItem.classList.add('active');
                }
                pageItem.innerHTML = `<a class="page-link" href="#">${i}</a>`;
                pageItem.onclick = (e) => {
                    e.preventDefault();
                    currentPage = i;
                    fetchOrders(currentPage, pageSize);
                    renderPagination();
                };
                pagination.appendChild(pageItem);
            }
    
            const nextPageItem = document.createElement('li');
            nextPageItem.className = `page-item ${currentPage === totalPages ? 'disabled' : ''}`;
            nextPageItem.innerHTML = `<a class="page-link" href="#">下一页</a>`;
            nextPageItem.onclick = (e) => {
                e.preventDefault();
                if (currentPage < totalPages) {
                    currentPage++;
                    fetchOrders(currentPage, pageSize);
                    renderPagination();
                }
            };
            pagination.appendChild(nextPageItem);
        }
    
        // 每页条数更改事件
        document.getElementById('pageSize').addEventListener('change', function () {
            pageSize = parseInt(this.value);
            fetchTotalRecords();
        });
    
        // 筛选按钮事件
        document.getElementById('filterButton').addEventListener('click', function () {
            currentPage = 1;
            fetchOrders(currentPage, pageSize);
        });
        function renderTable(orders) {
    const tableBody = document.getElementById('orderTableBody');
    tableBody.innerHTML = '';

    orders.forEach((order, index) => {
        const row = document.createElement('tr');
        const receiverInfo = `${order.baseInfo.buyerContact.name}, ${order.baseInfo.buyerContact.mobile}, ${order.baseInfo.buyerContact.province} ${order.baseInfo.buyerContact.city} ${order.baseInfo.buyerContact.area} ${order.baseInfo.buyerContact.address}`;
        row.innerHTML = 
            `<td>${(currentPage - 1) * pageSize + index + 1}</td>
            <td><input type="checkbox" class="order-checkbox" data-order-id="${order.baseInfo.id}"></td>
            <td class="order-id">${order.baseInfo.id}</td>
            <td class="buyer-name">
                <span class="receiver-info" data-order-id="${order.baseInfo.id}" data-oaid="${order.baseInfo.buyerContact.oaid}">${receiverInfo}</span>
            </td>
            <td>
                <img src="${order.productItems[0].productImgUrl[0]}" alt="${order.productItems[0].name}">
                ${order.productItems[0].skuInfos[0].value}
            </td>
            <td>${order.productItems[0].quantity}</td>
            <td>${(order.baseInfo.totalAmount / 100).toFixed(2)} 元</td>
            <td>${new Date(order.baseInfo.createTime).toLocaleString()}</td>`
        ;

        tableBody.appendChild(row);

        const receiverInfoSpan = row.querySelector('.receiver-info');
        receiverInfoSpan.addEventListener('click', function () {
            const orderId = this.getAttribute('data-order-id');
            const oaid = this.getAttribute('data-oaid');
            updateReceiverInfo(orderId, oaid, this);
        });
    });
}

function updateReceiverInfo(orderId, oaid, receiverInfoSpan) { 
    loadingMessage.style.display = 'flex';
    fetch(`http://localhost:8080/listOne?id=${orderId}&oaid=${oaid}`)
        .then(response => response.json())
        .then(data => {
            receiverInfoSpan.style.color = '#2730a5';
            receiverInfoSpan.style.fontWeight = 'bold';
            
            // 正确使用模板字面量进行字符串拼接
            const newReceiverInfo = `${data.result.ascpTradeContact.name}, ${data.result.ascpTradeContact.mobile}, ${data.result.ascpTradeContact.province}${data.result.ascpTradeContact.city}${data.result.ascpTradeContact.area}${data.result.ascpTradeContact.address}`;
            receiverInfoSpan.textContent = newReceiverInfo;
        })
        .catch(error => console.error('Error updating receiver info:', error))
        .finally(() => {
                    loadingMessage.style.display = 'none';
                });
}
document.getElementById('exportButton').addEventListener('click', function () {
    const selectedRows = Array.from(document.querySelectorAll('.order-checkbox:checked'))
        .map(checkbox => {
            // 找到勾选框所在的行
            const row = checkbox.closest('tr');
            return {
                "订单号": checkbox.getAttribute('data-order-id'),
                "收货人信息": row.cells[3].innerText,       // 假设第4列是数量
                "产品名": row.cells[4].innerText,
                "数量": row.cells[5].innerText   // 假设第5列是总金额
            };
        });

    if (selectedRows.length === 0) {
        alert('请先选择要导出的订单！');
        return;
    }

    // 创建工作簿
    const wb = XLSX.utils.book_new();
    const ws = XLSX.utils.json_to_sheet(selectedRows);

    // 将工作表添加到工作簿
    XLSX.utils.book_append_sheet(wb, ws, '订单信息');

    // 导出 Excel
    XLSX.writeFile(wb, '订单信息.xlsx');
});
document.getElementById('triggerButton').addEventListener('click', function () {
            const selectedCheckboxes = document.querySelectorAll('.order-checkbox:checked');
            const selectedRows = Array.from(selectedCheckboxes).map(checkbox => checkbox.closest('tr'));

            if (selectedRows.length === 0) {
                alert('请先选择要解密的订单！');
                return;
            }

            let currentIndex = 0;

            const triggerReceiverInfo = () => {
                if (currentIndex < selectedRows.length) {
                    const row = selectedRows[currentIndex];
                    const receiverInfoSpan = row.querySelector('.receiver-info');
                    const orderId = receiverInfoSpan.getAttribute('data-order-id');
                    const oaid = receiverInfoSpan.getAttribute('data-oaid');
                    
                    updateReceiverInfo(orderId, oaid, receiverInfoSpan);
                    currentIndex++;
                } else {
                    clearInterval(triggerInterval);
                    return;
                }
            };

            const waitingMessages = selectedRows.map(row => {
                const receiverInfoSpan = row.querySelector('.receiver-info');
                receiverInfoSpan.innerHTML += '<span class="waiting-message">（等待解密）</span>';
            });
            
            triggerReceiverInfo(); // 立即触发第一次
            isTriggering = true;
            triggerInterval = setInterval(() => {
                for (let i = 0; i < 1 && currentIndex < selectedRows.length; i++) {
                    triggerReceiverInfo();
                }
            }, 8000); // 每8秒触发一次
            window.addEventListener('beforeunload', function (event) {
            if (isTriggering) {
                event.preventDefault(); // 阻止默认行为
                event.returnValue = '正在解密数据，是否确认刷新？'; // 显示提示信息
            }
        });
        });
        // 选项卡切换
        document.querySelectorAll('.nav-link').forEach(tab => {
            tab.addEventListener('click', function (e) {
                e.preventDefault();
                document.querySelectorAll('.nav-link').forEach(t => t.classList.remove('active'));
                this.classList.add('active');
                currentStatus = this.dataset.status;
                currentPage = 1;
                fetchTotalRecords();
            });
        });
    
        // 设置默认日期并加载数据
        setDefaultDates();
        fetchTotalRecords();
    </script>
    
    <script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.18.5/xlsx.full.min.js"></script>

</body>
</html>
